package org.example.treeletter.service;

import org.example.treeletter.entity.Comment;
import org.example.treeletter.entity.Message;
import org.example.treeletter.entity.User;
import org.example.treeletter.repository.CommentRepository;
import org.example.treeletter.repository.MessageRepository;
import org.example.treeletter.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageRepository messageRepository;

    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public void saveMessage(String sign, String content, Integer userId) {
        Message message = new Message();
        message.setSign(sign);
        message.setUserId(userId);
        message.setContent(content);
        message.setCreationTime(new Date());
        messageRepository.save(message);
    }

    @Override
    public List<Message> getAllMessages() {
        return messageRepository.findAll();
    }

    @Override
    public void addComment(Integer messageID, String commentText , Integer userId, String userPhone,String creationTime) {
        Optional<Message> optionalMessage = messageRepository.findById(messageID);
        if (optionalMessage.isPresent()) {
            Message message = optionalMessage.get();
            Comment comment = new Comment();
            comment.setMessage(message);
            comment.setCommentText(commentText);
            comment.setUserId(userId);
            comment.setUserPhone(userPhone);
            comment.setCreationTime(Date.from(Instant.parse(creationTime))); // 解析时间戳
            commentRepository.save(comment);
        }
    }

    @Override
    public List<Comment> getCommentsForMessage(Integer messageID) {
        return commentRepository.findByMessage_Id(messageID);
    }

    @Override
    public void deleteMessageById(Integer MessageID) {
        // 检查信件是否存在
        Optional<Message> optionalMessage = messageRepository.findById(MessageID);
        if (!optionalMessage.isPresent()) {
            throw new RuntimeException("Message not found");
        }

        // 获取所有与该信件相关的评论
        List<Comment> comments = commentRepository.findByMessage_Id(MessageID);

        // 删除所有相关的评论
        for (Comment comment : comments) {
            commentRepository.delete(comment);
        }

        // 删除信件
        messageRepository.deleteById(MessageID);
    }


    @Override
    public void deleteCommentById(Integer commentID) {
        Optional<Comment> optionalComment = commentRepository.findById(commentID);
        if (optionalComment.isPresent()) {
            commentRepository.deleteById(commentID);
        } else {
            throw new RuntimeException("Comment not found");
        }
    }
    @Override
    public Message getMessageById(Integer messageID) {
        Optional<Message> optionalMessage = messageRepository.findById(messageID);
        return optionalMessage.orElse(null);
    }
    // 用户注册逻辑
    @Override
    public void registerUser(User user) {
        // 检查用户是否已经存在
        User existingUser = userRepository.findByPhone(user.getPhone());
        if (existingUser != null) {
            throw new RuntimeException("该手机号已注册");
        }

        // 保存新用户
        userRepository.save(user);
    }

    // 用户登录逻辑
    public User loginUser(String phone, String password) {
        User user = userRepository.findByPhone(phone);
        if (user == null || !user.getPassword().equals(password)) {
            throw new RuntimeException("登录失败");
        }
        return user;
    }
    @Override
    public List<Message> getMessagesByUserId(Integer userId) {
        return messageRepository.findByUserId(userId);
    }

    @Override
    public Message getRandomMessage() {
        List<Message> allMessages = messageRepository.findAll();
        if (allMessages.isEmpty()) {
            return null;
        }
        Random random = new Random();
        int index = random.nextInt(allMessages.size());
        return allMessages.get(index);
    }



    public Message getRandomMessageExcludingUserId(Integer userId) {
        List<Message> allMessages = messageRepository.findAll();
        List<Message> filteredMessages = allMessages.stream()
                .filter(message -> message.getUserId()!=null &&!message.getUserId().equals(userId))
                .collect(Collectors.toList());

        if (filteredMessages.isEmpty()) {
            return null;
        }

        Random random = new Random();
        int index = random.nextInt(filteredMessages.size());
        return filteredMessages.get(index);
    }
}